package com.lions.client.model;

import com.google.gwt.storage.client.Storage;
import com.lions.client.view.popup.MyPopupPanel;

public class HTMLStorage {

	public HTMLStorage() {
		if (!Storage.isLocalStorageSupported())
			new MyPopupPanel("HTML Storage Not Available",
					"Error: HTML Storage Not Available", "errorpopupwrapper");
	}

	/**
	 * Loads data from the session storage. This only loads modules at this
	 * time.
	 */
	public void storageLoad(ModuleList list) {
		final int ZERO = 0;
		final int SUBSTR = 6;

		ModuleList modList = list;
		listStore = Storage.getLocalStorageIfSupported();
		if (listStore != null) {
			for (int i = 0; i < listStore.getLength(); i++) {
				if (listStore.key(i).substring(ZERO, SUBSTR).equals("Module")) {
					modList.add(new Module(listStore.getItem("Module"
							+ new Integer(i).toString())));
				}
			}
		}
		listStore = null;
	}

	/**
	 * Adds a module to the local session storage, only accepts modules at this
	 * time.
	 * 
	 * @param mod
	 *            A module to add
	 */
	public void storageSaveAll(Model m) {
		ModuleList list = m.getModuleList();
		listStore = Storage.getLocalStorageIfSupported();
		if (listStore != null) {
			if (listStore.getLength() > 0) {
				listStore.clear();
			}
			for (int i = 0; i < list.size(); i++) {
				listStore.setItem("Module" + new Integer(i).toString(), list
						.get(i).toString());
			}
		} else {
			new MyPopupPanel("Error", "HTML Storage Save Failure");
		}
		listStore = null;
	}

	/**
	 * Clears all of the data within the local storage.
	 */
	public void storageClear(ModuleList list) {
		listStore = Storage.getLocalStorageIfSupported();
		if (listStore != null) {
			listStore.clear();
			list.clear();
		}
		listStore = null;
	}

	public int getStorageSize() {
		int size = 0;
		listStore = Storage.getLocalStorageIfSupported();
		if (listStore != null) {
			size = listStore.getLength();
		}
		return size;
	}

	private Storage listStore = null;
}
